const app = getApp()

/**
 *
 * @param url 请求地址
 * @param options 参数
 * @param items [{itemId: '',itemType: ''}]
 * @param timeout  最大等待时间 默认30秒
 * @param callback  接口完成的回调函数
 * @returns {Promise<unknown>}
 */
const request = (url, options, items, timeout = 30000, callback) => {
    return new Promise((resolve, reject) => {
        // 将用户所选择的行政区街道放置在请求体中
        let regions =  wx.getStorageSync('regions')
        if (!regions || regions.length === 0) {
            regions = []
        }

        let item = items ? {
            action: 'check',
            items
        } : {
            action: 'uncheck'
        }
        wx.request({
            url: `${app.globalData.host}${url}`,
            method: options.method,
            data: options.method === 'GET' ? options.data : JSON.stringify(options.data),
            timeout: timeout,
            header: {
                'Content-Type': 'application/json; charset=UTF-8',
                'token':wx.getStorageSync('token')
            },
            success(dataResponse) {
                let res = dataResponse.data;
                if (res.code === 200) {
                    resolve(res)
                } else if (res.code === 720 || res.code == 721) {
                    app.globalData.userInfo = undefined; // 注销登录
                    wx.showToast({
                        title: '登录信息已失效',
                        icon: 'none',
                        duration: 3000
                    })
                    reject(res)
                } else {
                    // 清除加载状态
                    wx.hideLoading()
                    wx.showToast({
                        title: res.message,
                        icon: 'error',
                        duration: 3000
                    })
                    reject(res)
                }
            },
            fail(error) {
                wx.hideLoading()
                wx.showToast({
                    title: '请求出错!!',
                    icon: 'error',
                    duration: 3000
                })
                reject(error.data)
            },
            complete(e) {
                if (callback) {
                    callback()
                }
            }
        })
    })
}
const get = (url, options = {}, items, timeout, callback) => {
    return request(url, {
        method: 'GET',
        data: options
    }, items, timeout, callback)
}
const post = (url, options, items, timeout, callback) => {
    return request(url, {
        method: 'POST',
        data: options
    }, items, timeout, callback)
}

module.exports = {
    get,
    post,
}